import { defineStore } from 'pinia';
import { Session } from '/@/utils/storage';
import { useLoginApi } from '/@/api/login/index';

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
	state: (): UserInfosState => ({
		userInfos: {
			tenantId: '',
			userId: '',
			userName: '',
			phoneNumber: '',
			phoneNumberVerified: false,
			photo: '',
			time: 0,
			roles: [],
			authBtnList: [],
		},
	}),
	actions: {
		async setUserInfos() {
			// 存储用户信息到浏览器缓存
			if (Session.get('userInfo')) {
				this.userInfos = Session.get('userInfo');
			} else {
				const userInfos = <UserInfos>await this.getApiUserInfo();
				this.userInfos = userInfos;
			}
		},
		// 获取用户信息
		async getApiUserInfo() {
			return new Promise((resolve) => {
				setTimeout(async () => {
					// 获取用户配置信息
					const appConfig = await <any>this.findApplicationConfig();

					// 权限
					let authBtnList: Array<string> = [];
					for(var role in appConfig.auth.grantedPolicies){
						if(appConfig.auth.grantedPolicies[role] != true){
							continue;
						}
						authBtnList.push(role);
					}
					
					// 用户信息
					const userInfos = {
						tenantId: appConfig.currentUser.tenantId,
						userId: appConfig.currentUser.id,
						userName: appConfig.currentUser.userName,
						phoneNumber: appConfig.currentUser.phoneNumber,
						phoneNumberVerified: appConfig.currentUser.phoneNumberVerified,
						photo: 'https://img2.baidu.com/it/u=1978192862,2048448374&fm=253&fmt=auto&app=138&f=JPEG?w=504&h=500',
						time: new Date().getTime(),
						roles: appConfig.currentUser.roles,
						authBtnList
					}

					// 存储
					Session.set('userInfo', userInfos);
					resolve(userInfos);
				}, 0);
			});
		},
		// 查询用户配置信息
		async findApplicationConfig(){
			return new Promise((resolve, reject) => {
				useLoginApi().getApplicationConfig().then((result: any) => {
					resolve(result);
				}).catch((err: any) => {
					reject(err);
				});
			});
		}
	}
});
